﻿using FactoryWebApplication.DataAccess;
using FactoryWebApplication.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Diagnostics;

namespace FactoryWebApplication.Controllers
{
    public class HomeController : Controller
    {
        readonly FactoryDbContext db;
        public HomeController(FactoryDbContext mySQL)
        {
            db = mySQL;
        }
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult MachineCode()
        {
            return View();
        }


        public IActionResult Save()
        {
            SDCard s = new SDCard();
            s.Id = Request.Form["sdId"];
            s.Capacity = Request.Form["sdCapacity"];
            s.Type = Request.Form["sdType"];
            s.SpeedGrade = Request.Form["sdSpeedGrade"];
            s.System = Request.Form["sdSystem"];

            Battery b = new Battery();
            b.Code = Request.Form["bCode"];
            b.Type = Request.Form["bType"];
            b.Size = Request.Form["bSize"];
            b.Capacity = Request.Form["bCapacity"];
            b.Temperature =Convert.ToInt16(Request.Form["temperature"]);
            b.Protection= Convert.ToInt16(Request.Form["protection"]);

            BatteryChip bc = new BatteryChip();
            bc.Code = Request.Form["bcCode"];
            bc.Remark = Request.Form["bcRemark"];

            Chip c = new Chip();
            c.Code = Request.Form["chCode"];
            c.Cpu = Request.Form["chCpu"];
            c.Mac = Request.Form["chMac"];
            c.AdaptationSystem = Request.Form["chAdaptationSystem"];

            Machine m = new Machine();
            m.Code = Request.Form["mCode"];
            m.Remark = Request.Form["mRemark"];
            m.B_code = Request.Form["bCode"];
            m.Bc_code = Request.Form["bcCode"];
            m.C_code = Request.Form["chCode"];


            try
            {
                db.sDCards.Add(s);
                db.batteries.Add(b);
                db.batteryChips.Add(bc);
                db.chips.Add(c);
                db.machines.Add(m);
                db.SaveChanges();

                return Ok(true);
            }
            catch(Exception ex) {
                return Ok(false);
            }


           
        }

        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
